import React from "react";

/**
 * 指定时间内更改返回值
 * @returns [React.MutableRefObject<T>, setTime]
 */
export const useChangeAwhile = <T>(defaultValue: T) => {
  const initialValue = React.useRef<T>(defaultValue);
  const timeoutId = React.useRef<number>();

  const suspend = (time: number, value: T) => {
    initialValue.current = value;
    if (timeoutId.current) {
      clearTimeout(timeoutId.current);
    }
    timeoutId.current = setTimeout(() => {
      initialValue.current = defaultValue;
    }, time);
  };
  return [initialValue, suspend] as [
    React.MutableRefObject<T>,
    (time: number, value: T) => void
  ];
};
